import sys
from pathlib import Path
from typing import Dict, Any, Optional, Tuple, Union, List

sys.path.append(str(Path(__file__).parent))
sys.path.append(str(Path(__file__).parent.parent.parent))
from get_device_fingerprint import get_device_fingerprint_info
from auth_integrated_login import AuthIntegratedLogin
from batch_sell_api import BatchSellOrderApi, BatchSellOrderRequest, CommodityItem


def integrated_login(mobile: str, area: str = "86", 
                     force_new_device: bool = False, 
                     device_info_file: str = "device_info.json") -> Dict[str, Any]:
    """集成登录方法
    
    先调用get_device_fingerprint获取设备ID和UK，
    再调用auth_integrated_login完成登录
    
    Args:
        mobile: 手机号码
        area: 区号，默认为中国区号86
        force_new_device: 是否强制生成新的设备信息，默认为False
        device_info_file: 设备信息文件路径，默认为当前目录下的device_info.json
        
    Returns:
        Dict[str, Any]: 登录成功后的用户信息，包括token、昵称等
    """
    print("=" * 50)
    print("集成登录服务")
    print("=" * 50)
    
    # 1. 获取设备指纹信息
    print("正在获取设备指纹信息...")
    android_id, device_id, uk = get_device_fingerprint_info(
        generate_new=force_new_device,
        file_path=device_info_file
    )
    
    if not device_id or not uk:
        raise Exception("获取设备指纹信息失败，无法登录")
    
    print(f"设备ID: {device_id}")
    print(f"UK值: {uk}")
    
    # 2. 使用获取到的设备信息进行登录
    print("正在初始化登录服务...")
    auth_login = AuthIntegratedLogin(device_id=device_id, uk=uk)
    
    # 3. 发送短信验证码
    print("\n===== 发送短信验证码 =====")
    result = auth_login.send_sms_code(mobile, area)
    
    user_info = None
    
    if isinstance(result, tuple):
        # 需要上行短信
        sms_content, sms_number = result
        print(f"请发送短信内容 '{sms_content}' 到号码 {sms_number}")
        
        # 测试短信上行登录
        print("\n===== 等待短信上行完成 =====")
        print("请在发送短信后，按Enter键继续...")
        input()
        
        try:
            user_info = auth_login.login_with_sms_up(mobile, area)
            print("短信上行登录成功！")
            print("\n===== 完整用户信息 =====")
            for key, value in user_info.items():
                if key == 'token':
                    print(f"{key}: {value[:30]}...")
                else:
                    print(f"{key}: {value}")
        except Exception as e:
            raise Exception(f"短信上行登录失败: {e}")
    else:
        # 短信验证码发送成功
        print(result)
        
        # 测试短信验证码登录
        print("\n===== 短信验证码登录 =====")
        code = input("请输入收到的验证码: ")
        
        try:
            user_info = auth_login.login_with_sms_code(mobile, code, area)
            print("短信验证码登录成功！")
            print("\n===== 完整用户信息 =====")
            for key, value in user_info.items():
                if key == 'token':
                    print(f"{key}: {value[:30]}...")
                else:
                    print(f"{key}: {value}")
        except Exception as e:
            raise Exception(f"短信验证码登录失败: {e}")
    
    # 将设备ID和UK添加到用户信息中，确保后续API调用能使用
    if user_info:
        if 'device_id' not in user_info:
            user_info['device_id'] = device_id
    
    return user_info


def submit_batch_order(user_info: Dict[str, Any], 
                       commodity_id: int, 
                       price: str, 
                       template_id: int,
                       buy_number: int = 1) -> Dict[str, Any]:
    """提交批量卖单
    
    Args:
        user_info: 用户信息，包含token、uk等
        commodity_id: 商品ID
        price: 商品价格
        template_id: 模板ID
        buy_number: 购买数量，默认为1
        
    Returns:
        Dict[str, Any]: 订单创建结果
    """
    print("\n" + "=" * 50)
    print("批量卖单服务")
    print("=" * 50)
    
    # 从用户信息中获取必要参数
    device_id = user_info.get("device_id", "")
    auth_token = user_info.get("token", "")
    uk = user_info.get("uk", "")
    
    if not device_id:
        raise Exception("缺少设备ID，无法提交订单")
    
    if not uk:
        raise Exception("缺少UK值，无法提交订单")
    
    if not auth_token:
        raise Exception("缺少授权令牌，无法提交订单")
    
    if not auth_token.startswith("Bearer "):
        auth_token = f"Bearer {auth_token}"
    
    print(f"使用设备ID: {device_id}")
    print(f"使用UK值: {uk}")
    print(f"使用授权令牌: {auth_token[:30]}...")
    
    # 创建API实例
    api = BatchSellOrderApi(
        device_token=device_id,
        device_id=device_id,
        auth_token=auth_token,
        uk=uk
    )
    
    # 创建商品列表
    commodity_list = [
        CommodityItem(
            commodityId=commodity_id,
            commodityIdPrice=price,
            templateId=template_id
        )
    ]
    
    # 创建请求对象
    request = BatchSellOrderRequest(
        buyNumber=buy_number,
        commodityList=commodity_list,
        orderSubType=9,
        paySellAmount=price,
        templateId=template_id,
        unitPrice=price,
        Sessionid=device_id  # 确保使用设备ID作为会话ID
    )
    
    try:
        # 发送请求
        result = api.create_batch_order(request)
        
        # 打印结果
        print("批量卖单创建成功！")
        print(f"订单号: {result.orderNo}")
        print(f"支付订单号: {result.payOrderNo}")
        print(f"等待支付数据号: {result.waitPaymentDataNo}")
        
        # 返回结果
        return {
            "orderNo": result.orderNo,
            "payOrderNo": result.payOrderNo,
            "waitPaymentDataNo": result.waitPaymentDataNo,
            "payString": result.payString,
            "batchOrderNo": result.batchOrderNo
        }
    except Exception as e:
        print(f"批量卖单创建失败: {e}")
        raise


def integrated_login_and_order(mobile: str, 
                              commodity_id: int,
                              price: str,
                              template_id: int,
                              area: str = "86",
                              force_new_device: bool = False,
                              device_info_file: str = "device_info.json") -> Tuple[Dict[str, Any], Dict[str, Any]]:
    """集成登录并提交订单
    
    先完成登录流程，然后使用登录信息提交批量卖单
    
    Args:
        mobile: 手机号码
        commodity_id: 商品ID
        price: 商品价格
        template_id: 模板ID
        area: 区号，默认为中国区号86
        force_new_device: 是否强制生成新的设备信息，默认为False
        device_info_file: 设备信息文件路径，默认为当前目录下的device_info.json
        
    Returns:
        Tuple[Dict[str, Any], Dict[str, Any]]: (用户信息, 订单信息)
    """
    # 1. 完成登录流程
    user_info = integrated_login(mobile, area, force_new_device, device_info_file)
    
    # 2. 提交批量卖单
    order_info = submit_batch_order(
        user_info=user_info,
        commodity_id=commodity_id,
        price=price,
        template_id=template_id
    )
    
    return user_info, order_info


def main():
    """测试集成登录功能"""
    try:
        print("===== 集成登录和批量卖单测试 =====")
        print("1. 仅登录")
        print("2. 登录并提交订单")
        choice = input("请选择功能(1-2): ")
        
        # 测试手机号
        mobile = input("请输入手机号码: ")
        
        # 是否使用新设备
        force_new = input("是否强制生成新的设备信息？(y/n，默认n): ").lower() == 'y'
        
        if choice == "2":
            # 获取订单信息
            commodity_id = int(input("请输入商品ID: "))
            price = input("请输入商品价格: ")
            template_id = int(input("请输入模板ID: "))
            
            # 登录并提交订单
            user_info, order_info = integrated_login_and_order(
                mobile=mobile,
                commodity_id=commodity_id,
                price=price,
                template_id=template_id,
                force_new_device=force_new
            )
            
            print("\n===== 订单创建结果 =====")
            for key, value in order_info.items():
                print(f"{key}: {value}")
        else:
            # 仅登录
            user_info = integrated_login(mobile, force_new_device=force_new)
            
            print("\n登录成功，完整用户信息:")
            for key, value in user_info.items():
                if key == 'token':
                    print(f"{key}: {value[:30]}...")
                else:
                    print(f"{key}: {value}")
    except Exception as e:
        print(f"\n操作失败: {e}")


if __name__ == "__main__":
    main()
